﻿using System.IO;
using System.Windows.Forms;

namespace MP2
{
    class Writer
    {
        public FileStream ISOStream;
        
        static readonly byte[] SS_HEADER = new byte[] { 225, 15, 49, 16, 0, 4, 251, 32 };

        /// <summary>
        /// Creates a new instance of a Streamwriter. 
        /// </summary>
        /// <param name="ISO_Location">String referencing the location of target ISO</param>
        public bool CreateWriter(string ISO_Location)
        {
            try
            {
                ISOStream = new FileStream(ISO_Location, FileMode.Open);
                return true;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Mousepatcher 2.0");
                return false;
            }
        }

        /// <summary>
        /// Writes the SS and DMI files into the target ISO.
        /// </summary>
        /// <param name="SS_Location">File path of the SS or DMI file.</param>
        /// <param name="SS_Offset">Offset where the file must be written to.</param>
        public void SS_Writer(string SS_Location, long SS_Offset)
        {
            try
            {
                FileStream SS_FILESTREAM = File.OpenRead(SS_Location);

                //Read into a byte array.
                byte[] SS_ARRAY = new byte[2048];
                SS_FILESTREAM.Read(SS_ARRAY, 0, 2048);

                BinaryWriter SS_BINWRITER = new BinaryWriter(ISOStream);
                SS_BINWRITER.BaseStream.Position = SS_Offset;
                SS_BINWRITER.Write(SS_ARRAY, 0, 2048);
                SS_BINWRITER.Flush();
            }
            catch (System.Exception ex)
            { MessageBox.Show("EXCEPTION @:" + ex.TargetSite + "\nMESSAGE:" + ex.Message, "Mousepatcher 2.0"); }
        }

        #region File Checks (Verifies Size, Format etc)
        public bool CheckISO(string ISO_Location)
        {
            FileInfo ISOInfo = new FileInfo(ISO_Location);
            bool ExtensionValid = false;
            bool SizeValid = false;

            //Only ISO and 000 files are correct X360 images. Only accept 'em.
            //TODO: Investigate whether BIN/CUE format is okay. No reports so far though.
            if ((ISOInfo.Extension.ToLower() == ".iso") || (ISOInfo.Extension.ToLower() == ".000"))
            { ExtensionValid = true; }
            else { MessageBox.Show("File Error:\n" + ISO_Location + " is not a valid Xbox 360 ISO image.\nReason: Not a valid extension.", "Mousepatcher 2.0"); }

            //Size Check. Is the size of the ISO over 7gb? 
            //(Why've I put 5gb as min check? There was probably method to my madness when I did this...)
            if (ISOInfo.Length > 5000000000)
            { SizeValid = true; }
            else { MessageBox.Show("File Error:\n" + ISO_Location + " is not a valid Xbox 360 ISO image.\nReason: Not large enough.", "Mousepatcher 2.0"); }

            //Okay, after the preliminary checks.. Is the ISO dropped valid?
            if (ExtensionValid && SizeValid)
            { return true; }
            else
            { return false; }
        }
        public bool CheckSS(string SS_Location)
        {
            FileInfo SS_INFO = new FileInfo(SS_Location);

            if (SS_INFO.Length == 2048)
            {
                try
                {
                    FileStream SSFS = new FileStream(SS_Location, FileMode.Open);
                    BinaryReader SS_READER = new BinaryReader(SSFS);

                    byte[] SS_COMPARE = SS_READER.ReadBytes(8);

                    for (int i = 0; i < 7; i++)
                    {
                        if (SS_COMPARE[i] != SS_HEADER[i])
                        { SSFS.Close(); return false; }
                    }

                    //First 8 bytes match the header. Must be an SS File!
                    SSFS.Close();
                    return true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("SS File is not valid:\n" + ex.Message, "Mousepatcher 2.0", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            else
            {
                MessageBox.Show("SS File is not 2048 bytes in size.", "Mousepatcher 2.0", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public bool CheckDMI(string DMI_Location)
        {
            /* 
             * TODO: Get a decent, secure DMI check!
             * TODO: Consider using ISOs Media ID for Auto.
             * TODO: Consider using SS/DMI Timestamp comparison for Manual. (Thanks ABGX360!)
             */
            try
            {
                FileInfo DMI_FI = new FileInfo(DMI_Location);
                if (DMI_FI.Length == 2048) { return true; }
                else
                {
                    MessageBox.Show("SS File is not 2048 bytes in size.", "Mousepatcher 2.0", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("DMI File is not valid:\n" + ex.Message, "Mousepatcher 2.0", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion
    }
}
